package com.tech.tool.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

@Slf4j
public class HttpUtil {

    public static String get(String url, String query, String cookie) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            // 创建Http Get请求
            HttpGet httpGet = new HttpGet(url);
            // 设置cookie
            if (cookie != "") {
                setCookie(httpGet, cookie);
            }
            result = getResponse(httpClient, httpGet);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String post(String url, String data, String cookie) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(data, ContentType.APPLICATION_JSON);
            // 设置cookie
            setCookie(httpPost, cookie);
            httpPost.setEntity(entity);
            result = getResponse(httpClient, httpPost);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void setCookie(HttpRequestBase request, String cookie) {
        request.addHeader("Cookie", cookie);
    }

    public static String getResponse(CloseableHttpClient httpClient, HttpRequestBase request) {
        CloseableHttpResponse response = null;
        String result = "";
        try {
            response = httpClient.execute(request);
            HttpEntity a = response.getEntity();
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            log.info(resultString);
            result = resultString;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return result;
    }
}
